package org.x4444.trans;

public class TransUtils {

    public static String getEventDt(String in) {
        // field #6
        int del6Index = getDelIndex(in, -1, 5, '|');
        
        String eventDt = in.substring(del6Index + 1, del6Index + 11);
        return eventDt;
    }

    public static String getIssueSymId(String in) {
        // field #5
        String issue = getField(in, 5, '|');
        if ("#".equals(issue)) {
            return null;
        }
        return issue;
    }
    
    public static String getOatsProcDt(String in) {
        // field #33
        int del33Index = getDelIndex(in, -1, 32, '|');
        
        String procDt = in.substring(del33Index + 1, del33Index + 11);
        return procDt;
    }

    public static int getIssueHashCd(String issueSymId) {
        int issueHashCd = Math.abs(issueSymId.hashCode()) % 50;
        return issueHashCd;
    }

    /**
     * Position, starts with 1
     */
    public static String getField(String line, int pos, char delim) {
        int ipos = getDelIndex(line, -1, pos - 1, '|');
        int nextiPos = getDelIndex(line, ipos, 1, '|');
        
        String res = line.substring(ipos + 1, nextiPos);
        return res;
    }
    
    public static int getDelIndex(String line, int initPos, int delN, char delim) {
        int pos = initPos;
        for (int i = 0; i < delN; i++) {
            pos = line.indexOf(delim, pos + 1);
            char esc = line.charAt(pos - 1);
            if (esc == '\\') {
                char esc2 = line.charAt(pos - 2);
                if (esc2 != '\\') {
                    i--;
                    continue;
                }
            }
        }
        return pos;
    }
    
}
